﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Insteon.Messages.Insteon
{
    internal class ExtendedMessage : Message
    {
        internal const int MessCommand = 0x51;
        internal const int MessLength = 25;
        internal const int MessFlagsByte = 8;
        internal const int MessSizeBit = 0;

        internal readonly InsteonAddress To;
        internal readonly InsteonAddress From;
        internal readonly byte Command1;
        internal readonly byte Command2;
        internal readonly Flags Flags;
        internal readonly byte[] UserData = new byte[14];

        public ExtendedMessage(byte[] buffer, UInt16 Length, UInt64 Number, out UInt16 Size)
            : base(buffer, Length, Number)
        {
            if (!Check(buffer, Length))
            {
                throw new Exception("Invalid message format");
            }
            To = new InsteonAddress(buffer, 5);
            From = new InsteonAddress(buffer, 2);
            Command1 = buffer[9];
            Command2 = buffer[10];
            Flags = new Flags(buffer[MessFlagsByte]);
            for (int t = 0; t < 14; t++)
            {
                UserData[t] = Buffer[t+11];
            }
            Size = MessLength;
        }

        internal static bool Check(byte[] buffer, UInt16 length)
        {
            if ((length >= MessLength) && (buffer[1] == MessCommand))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public override string ToString()
        {
            return String.Format("({0}) RecvExtMesssage - To: {1} From: {2} C1:{3:x2} C2:{4:x2} {5}\r\n" +
                                    "U1:{6:x2} U2:{7:x2} U1:{8:x2} U2:{9:x2} U1:{10:x2} U2:{11:x2} U1:{12:x2} U2:{13:x2} U1:{14:x2} U2:{15:x2} U1:{16:x2} U2:{17:x2} U1:{18:x2} U2:{19:x2} ", 
                                    Number, To, From, Command1, Command2, Flags,
                                    UserData[0], UserData[1], UserData[2], UserData[3], UserData[4], UserData[5], UserData[6], 
                                    UserData[7], UserData[8], UserData[9], UserData[10], UserData[11], UserData[12], UserData[13]);
        }

        internal override void RouteToDevice(InsteonInterface Interface)
        {
            Interface.RouteToTarget(this, To);
            Interface.RouteToTarget(this, From);
        }
    }
}
